﻿using BaseUi.Device;
using HandyControl.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
using Ping9719.DeviceCommunication.Clients.Modbus;
using System.Windows.Forms;
using MessageBox = HandyControl.Controls.MessageBox;
using BaseUi.Models;

namespace BaseUi.ViewModel
{
    public class MainViewModel : BindableBase
    {
        Mutex mutex;
        private string title = string.Empty;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get => title; set { SetProperty(ref title, value); } }
        private bool Electrical_;
        public bool Electrical { get => Electrical_; set { SetProperty(ref Electrical_, value); } }
        private bool Toggle_;
        public bool Toggle { get => Toggle_; set { SetProperty(ref Toggle_, value); } }
        private bool Test_;
        public bool Test { get => Test_; set { SetProperty(ref Test_, value); } }
        private bool Raster_;
        public bool Raster { get => Raster_; set { SetProperty(ref Raster_, value); } }
        private bool Scram_;
        public bool Scram { get => Scram_; set { SetProperty(ref Scram_, value); } }
        private bool Switch_ ;
        public bool Switch { get => Switch_; set { SetProperty(ref Switch_, value); } }

        private bool Changpage_;
        public bool Changpage { get => Changpage_; set { SetProperty(ref Changpage_, value); } }

        private bool Vision_;
        public bool Vision { get => Vision_; set { SetProperty(ref Vision_, value); } }
        public bool Isenable_=false;
        public bool Isenable { get => Isenable_=(HomeView.viewModel.RunState!=RunState.Run); set { SetProperty(ref Isenable_, value); } }
        public string[] msg = new string[] { };
        public bool ischengg=false;
        public string errtext ;
        #region 专用_MainWindow2
        //隐藏式选项卡的高度
        public double TabItemHeight { get; set; } = 0;

        private string SelectedValue_ = "主页";
        public string SelectedValue { get => SelectedValue_; set { SetProperty(ref SelectedValue_, value); } }
        #endregion

        private DateTime time;
        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Time { get => time; set { SetProperty(ref time, value); } }
        /// <summary>
        /// 在初始化前的相关检查
        /// </summary>
        public bool InitAgo()
        {
            //只允许打开一个
            mutex = new Mutex(true, string.Concat("MengXunBaseUi", Path.GetFileNameWithoutExtension(LocalFile.AppName)), out bool createdNew);
            if (!createdNew)
            {
                MessageBox.Warning("已有实列在运行！", "提示");
                return false;
            }
            byte[] sg=new byte[] { };
           var ss =  Ping9719.DeviceCommunication.Common.Helpers.DataConvert.ByteArrayToString(sg);
            //初始化
            Tuple<string, string, Action>[] tuples = new Tuple<string, string, Action>[]
            {
                new Tuple<string, string, Action>("检测文件..", "缺少文件，尝试将项目[data/]中的所有文件复制到[bin/data/]中", () =>
                {
                    if(!System.IO.File.Exists(LocalFile.ConfigPath)||!System.IO.File.Exists(LocalFile.PlcDotPath))
                        throw new Exception("缺少文件，请尝试将项目[data/]中的所有文件复制到[bin/data/]中");
                }),
                new Tuple<string, string, Action>("检测文件..", "配置文件中没有内容，请联系管理员", () =>
                {
                    if(string.IsNullOrWhiteSpace(System.IO.File.ReadAllText(LocalFile.ConfigPath, Encoding.UTF8)))
                        throw new Exception($"配置文件[{LocalFile.ConfigPath}]中没有内容");
                }),
                new Tuple<string, string, Action>("初始化数据中..", "初始化数据库失败，请联系管理员", () =>
                {
                    AuthDb.Ini();
                    DataDb.Inidata();

                    //var dt = DateTime.Now;
                    //var data = new BoxInfo()
                    //{
                    //Num = 1,
                    //State = "ng1",
                    //IsOk=false,
                    //Time = dt,
                    //};
                    //AuthDb.dbBox.Insertable(data).ExecuteCommand();
                    //var info = AuthDb.dbBox.Queryable<BoxInfo>().Where(o => o.Id != 0).ToList();
                    //WarnInfoDb.Ini();
                }),
                //new Tuple<string, string, Action>("初始化RFID中..", "RFID连接失败，请检查串口", () =>
                //{

                //}),
                //new Tuple<string, string, Action>("连接机器人中..", "机器人连接失败，请检查是否打开软件", () =>
                //{

                //}),
                new Tuple<string, string, Action>("连接串口中..", "串口连接失败，请检查网络", () =>
                {
                    //var dd = LocalFile.Config.MESjoggle;
                    //var ss = LocalFile.Config.Block;
                    LocalStatic.Electric = new DianQiBan(LocalFile.Config.Electric);
                    LocalStatic.Test = new CeShiBan[]
                    {
                        new CeShiBan(LocalFile.Config.Text1),
                        new CeShiBan(LocalFile.Config.Text2),
                        new CeShiBan(LocalFile.Config.Text3),
                        new CeShiBan(LocalFile.Config.Text4),
                    };
                    LocalStatic.Change1 = new ChangeBan(LocalFile.Config.Change1);
                    LocalStatic.Change2 = new ChangeBan(LocalFile.Config.Change2);
                    //var res=LocalStatic.Electric.Open();
                    //LocalStatic.Plc = new SiemensS7Client(SiemensVersion.S7_1200,ipPort.Address,ipPort.Port);
                    //var res=LocalStatic.Plc.Open();
                    //if (!res.IsSucceed)
                    //    throw new Exception(res.Err);
                }),
                new Tuple<string, string, Action>("连接视觉中..", "视觉连接失败，请检查网络", () =>
                {
                    var ipPort1 = LocalFile.Config.Vision1.ToIpPort();
                    LocalStatic.Vision1 = new VisionBan(ipPort1.Address,ipPort1.Port);
                    //var res=LocalStatic.Vision1.Open();
                    //if (!res.IsSucceed)
                    //    throw new Exception(res.Err);
                    var ipPort2 = LocalFile.Config.Vision2.ToIpPort();
                    LocalStatic.Vision2 = new VisionBan(ipPort2.Address,ipPort2.Port);
                    //var res1=LocalStatic.Vision2.Open();
                    //if (!res1.IsSucceed)
                    //    throw new Exception(res1.Err);
                }),
            };
            MainLoadWindow.TaskSleepTime = 200;
            if (!MainLoadWindow.Show(tuples))
                return false;

            Task.Run(LoadWhileTask);
            //清理日志
            Task.Run(() =>
            {
                if (LocalFile.Config.Sys.SaveLogDay < 0)
                    return;

                var t = TimeSpan.FromDays(LocalFile.Config.Sys.SaveLogDay);
                Logs.Clear(t);
                WarnInfoDb.Clear(t);
            });

            //json转换器
            {
                //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                //{
                //    Converters = new[] { new JsonDateTimeConverter() },
                //};
            }

            //不登录，直接使用最高权限
            {
                //UserLoginView.NotLogin();
                //return true;
            }
            //登录
            {
                var userLoginView = new UserLoginView();
                var isok = userLoginView.ShowDialog() == true;
                userLoginView = null;
                Logs.Write(UserInfoView.viewModel.LoginName + "登录", LogsType.configuration);
                return isok;
            }

        }

        /// <summary>
        /// 初始化并运行时间
        /// </summary>
        public async void Init(System.Windows.Window window)
        {
            //加载 程序名称
            var versionInfo = FileVersionInfo.GetVersionInfo(LocalFile.AppPath);
            Title = $"{versionInfo.ProductName}  V{Version.Parse(versionInfo.FileVersion).ToString(2)}";
            //Title = $"显示板自动检测程序 V{ Version.Parse(versionInfo.FileVersion).ToString(2)}";

            //加载 窗体模式
            if (LocalFile.Config.Sys.StartupFull)
                window.WindowState = System.Windows.WindowState.Maximized;

            //注册 设备
            IotDevice.UserChange = ((iot) =>
            {
                if (string.IsNullOrEmpty(iot.Funct))
                    Growl.Info($"你点击了[{iot.Name}]，尝试改为[{iot.Val}]");
                else
                    Growl.Info($"你点击了[{iot.Name}][{iot.Funct}]，尝试改为[{iot.Val}]");

                Logs.Write(iot, LogsType.DeviceHand);
            });

            //注册 日志
            TextBoxLog.TextBoxLogAdd = ((info) =>
            {
                if (info.Tag is LogsType logsType)
                    Logs.Write(info.Text, logsType, info.Time);
                else
                    Logs.Write(info.Text, LogsType.Info, info.Time);
            });

            //加载 时钟
            while (true)
            {
                Time = DateTime.Now;
                await Task.Delay(1000);
            }
        }

        public ICommand OpenUserCommand { get => new DelegateCommand(OpenUser); }
        /// <summary>
        /// 打开用户
        /// </summary>
        public void OpenUser()
        {
            if (UserInfoView.viewModel.IsLogin)
            {
                var userInfoView = new UserInfoView();
                userInfoView.ShowDialog();

                if (userInfoView.IsExitLogin)
                {
                    SelectedValue = "主页";
                    Growl.Info("您已退出登录。");

                    Logs.Write(UserInfoView.viewModel.LoginName + "退出登录", LogsType.configuration);
                    if (HomeView.viewModel.RunState!=RunState.Stop)
                    {
                        TextBoxLog.AddLog("退出登录停止生产流程");
                        HomeView.viewModel.Stop();
                    }
                    userInfoView = null;
                }
            }
            else
            {
                var userLoginView = new UserLoginView();

                //登录成功
                if (userLoginView.ShowDialog() == true)
                {
                    Growl.Success($"欢迎您：{UserInfoView.viewModel.LoginName}");

                    Logs.Write(UserInfoView.viewModel.LoginName + "登录", LogsType.configuration);
                    userLoginView = null;
                }
            }
        }

        public ICommand OpenLogCommand { get => new DelegateCommand(OpenLog); }
        /// <summary>
        /// 打开日记
        /// </summary>
        public void OpenLog()
        {
            if (!System.IO.Directory.Exists(LocalFile.LogDir))
            {
                Growl.Info("暂时没有日志。");
                return;
            }

            try
            {
                Folder.OpenFolder(LocalFile.LogDir);
            }
            catch (Exception)
            {
                Growl.Error("打开日志目录失败。");
            }
        }

        public ICommand OpenHelpCommand { get => new DelegateCommand(OpenHelp); }
        /// <summary>
        /// 打开帮助
        /// </summary>
        public void OpenHelp()
        {
            if (!System.IO.File.Exists(LocalFile.DocPath))
            {
                Growl.Info("帮助文档正在书写中。");
                return;
            }

            try
            {
                Folder.OpenFolderAndSelectedFile(LocalFile.DocPath);
            }
            catch (Exception)
            {
                Growl.Error("打开帮助文档失败。");
            }
        }

        public ICommand OpenWeCommand { get => new DelegateCommand(OpenWe); }
        /// <summary>
        /// 打开关于
        /// </summary>
        public void OpenWe()
        {
            var aboutView = new AboutView();
            aboutView.ShowDialog();
            aboutView = null;
        }

        public void LoadWhileTask()
        {
            while (true)
            {
                Thread.Sleep(20);

                Electrical= LocalStatic.Electric.open();
                if (!Electrical)
                {
                    HomeView.viewModel.AddTempTextErr("电气COM口", new string[] { "COM口被占用或关闭" + DateTime.Now.ToString() });
                }
                Toggle= LocalStatic.Change1.open()&&LocalStatic.Change2.open();
                if (!Toggle)
                {
                    //HomeView.viewModel.AddTempTextErr("切换COM口", new string[] { "COM口被占用或关闭" + DateTime.Now.ToString() });
                    if (LocalStatic.Change1.isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("切换1COM口", new string[] { $"切换COM口1的{LocalFile.Config.Change1}被占用或关闭" + DateTime.Now.ToString() });
                    }
                    if (LocalStatic.Change2.isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("切换2COM口", new string[] { $"切换COM口2的{LocalFile.Config.Change2}被占用或关闭" + DateTime.Now.ToString() });
                    }
                }

                Test = LocalStatic.Test[0].open() && LocalStatic.Test[1].open() && LocalStatic.Test[2].open() && LocalStatic.Test[3].open();
                if (!Test)
                {
                    //HomeView.viewModel.AddTempTextErr("测试COM口", new string[] { "COM口被占用或关闭" + DateTime.Now.ToString() });
                    if (LocalStatic.Test[0].isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("1号测试位COM口", new string[] { $"{LocalStatic.Test[0].name}被占用或关闭" + DateTime.Now.ToString() });
                    }
                    if (LocalStatic.Test[1].isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("2号测试位COM口", new string[] { $"{LocalStatic.Test[1].name}被占用或关闭" + DateTime.Now.ToString() });
                    }
                    if (LocalStatic.Test[2].isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("3号测试位COM口", new string[] { $"{LocalStatic.Test[2].name}被占用或关闭" + DateTime.Now.ToString() });
                    }
                    if (LocalStatic.Test[3].isopen == false)
                    {
                        HomeView.viewModel.AddTempTextErr("4号测试位COM口", new string[] { $"{LocalStatic.Test[3].name}被占用或关闭" + DateTime.Now.ToString() });
                    }
                }
                Vision = LocalStatic.Vision1.connect && LocalStatic.Vision2.connect;
                if (!Vision)
                {
                    //    var ipPort1 = LocalFile.Config.Vision1.ToIpPort();
                    //    LocalStatic.Vision1.open(ipPort1.Address, ipPort1.Port);
                    HomeView.viewModel.AddTempTextErr("视觉通信", new string[] { "视觉软件未打开或服务器未启动" + DateTime.Now.ToString() });
                }
                var aaa = LocalStatic.Electric.Readsentfrequency(500, PortModel.EAll, LocalFile.Config.Address);
                if (aaa.IsSucceed)
                {
                    ischengg = true;
                    msg = aaa.Value.Split(' ');
                    if (msg[6] == "00")//开箱感应
                    {
                        Switch = true;
                        if (HomeView.viewModel.RunState == RunState.Run)
                        {
                            HomeView.viewModel.AddTempTextErr("开关箱", new string[] { "开关箱暂停" + DateTime.Now.ToString() });
                            TextBoxLog.AddLog("开关箱暂停");
                            HomeView.viewModel.Pause();
                        }
                        //return;
                    }
                    else
                    {
                        Switch = false;
                    }
                    if (msg[8] == "01")//急停
                    {
                        Scram = true;
                        if (HomeView.viewModel.RunState == RunState.Run)
                        {
                            HomeView.viewModel.AddTempTextErr("按钮", new string[] { "急停按钮暂停" + DateTime.Now.ToString() });
                            TextBoxLog.AddLog("急停按钮暂停");
                            HomeView.viewModel.Pause();
                        }
                        //return;
                    }
                    else
                    {
                        Scram = false;
                    }
                    if (msg[9] == "01")//光栅
                    {
                        Raster = true;
                        if (HomeView.viewModel.RunState == RunState.Run)
                        {
                            if (HomeView.viewModel.directioning == true)
                            {
                                Growl.Error("旋转过程中光栅暂停");
                                HomeView.viewModel.AddTempTextErr("光栅", new string[] { "光栅暂停" + DateTime.Now.ToString() });
                                TextBoxLog.AddLog("光栅暂停");
                                HomeView.viewModel.Pause();
                            }
                        }
                        //return;
                    }
                    else
                    {
                        Raster = false;
                    }
                }
                else
                {
                    ischengg = false;
                    errtext = aaa.Err;
                }
                var togo = LocalStatic.Electric.Readsenttogo(500, LocalFile.Config.Address);
                if (togo.IsSucceed)
                {
                    //if (togo.Value == PortModel.start1|| togo.Value == PortModel.start2)
                    //{
                    //    TextBoxLog.AddLog("非运行状态禁止启动");
                    //}
                    if (HomeView.viewModel.RunState == RunState.Run)
                    {
                        if (!HomeView.viewModel.Working)
                        {
                            if (togo.Value == PortModel.start1)
                            {
                                if (!HomeView.viewModel.Working)
                                {
                                    TextBoxLog.AddLog("启动");
                                    HomeView.viewModel.runstart = 1;
                                }
                                else
                                {
                                    TextBoxLog.AddLog("启动失败正在进行测试中");
                                }
                            }
                            else if (togo.Value == PortModel.start2)
                            {
                                if (!HomeView.viewModel.Working)
                                {
                                    TextBoxLog.AddLog("强制启动");
                                    HomeView.viewModel.runstart = 2;
                                }
                                else
                                {
                                    TextBoxLog.AddLog("强制启动失败正在进行测试中");
                                }
                            }
                        }
                        
                    }
                    else
                    {
                        if (togo.Value == PortModel.start1|| togo.Value == PortModel.start2)
                        {
                            TextBoxLog.AddLog("非运行状态禁止启动");
                        }
                    }
                }
            }
        }
    }
}
